from django import forms
from .models import Image
from urllib import request
from django.core.files.base import ContentFile
from django.utils.text import slugify
class ImageCreateForm(forms.ModelForm):
	class Meta:
		model = Image
		fields = ('title','url','description')

	def clean_url(self):
		url = self.cleaned_data['url']
		valid_extensions = ['jpg','jpeg']
		extension = url.rsplit('.',1)[1].lower()
		if extension not in valid_extensions:
			raise forms.ValidationError("The given url does not match valid image extenions")
		return url

	def save(self,force_insert=False,force_update=False,commit=True):
		#从表单中新建一个image对象
		image = super(ImageCreateForm,self).save(commit = False)
		# 从表单的cleaned_data字典中获取URL
		image_url = self.cleaned_data['url']
		#通过标题和源文件拓展名生成图片名字
		image_name = '{}.{}'.format(slugify(image.title),image_url.rsplit('.',1)[1].lower())
		#使用urllib模块下载图片，
		response = request.urlopen(image_url)
		#调用save()方法把图片传递给一个ContentFiel对象，这个对象被下载的文件所实例化
		#我们的文件保存到项目中的media 路径下
		image.image.save(image_name,ContentFile(response.read()),save=False)
		#为了保持和我们覆写的save()方法一样的行为，我们将在commit参数为Ture时保存表单到数据库中
		if commit:
			image.save()
		return image



